using System;
using System.Collections.Specialized;
using Avalonia.Controls;
using RawRestructure.ViewModels;

namespace RawRestructure.Views;

/// <summary>
/// 主窗口
/// </summary>
public partial class MainWindow : Window
{
    private ListBox? _logListBox;
    
    public MainWindow()
    {
        InitializeComponent();
        
        // 获取ListBox引用
        _logListBox = this.FindControl<ListBox>("LogListBox");
        
        // 等待DataContext设置完成（确保ViewModels已加载）
        this.DataContextChanged += MainWindow_DataContextChanged;
    }
    
    private void MainWindow_DataContextChanged(object? sender, EventArgs e)
    {
        if (_logListBox != null && DataContext is MainWindowViewModel viewModel)
        {
            // 监听LogMessages集合变化
            viewModel.LogMessages.CollectionChanged += LogMessages_CollectionChanged;
        }
    }

    private void LogMessages_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
    {
        // 当有新项添加时，滚动到最后一项
        if (e.Action == NotifyCollectionChangedAction.Add && _logListBox != null && _logListBox.ItemCount > 0)
        {
            _logListBox.ScrollIntoView(_logListBox.ItemCount - 1);
        }
    }
} 